package com.lagou.edu.support;/**
 * Created by IntelliJ IDEA.
 * User: Yangdx.
 * Date: 2020/5/8.
 * Time: 2:26.
 * Tags: Code, we are serious.
 */

import com.lagou.edu.stereotype.Transactional;
import com.lagou.edu.utils.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @author
 * @create 2020-05-08 2:26
 **/
public class AnnotationTransactionInvocationHandler implements InvocationHandler {
    private Object proxied;
    private TransactionManager transactionManager;

    AnnotationTransactionInvocationHandler(Object object, TransactionManager transactionManager) {
        this.proxied = object;
        this.transactionManager = transactionManager;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] objects) throws Throwable {
        Method originalMethod = proxied.getClass().getMethod(method.getName(), method.getParameterTypes());
        if (!originalMethod.isAnnotationPresent(Transactional.class)) {
            return method.invoke(proxied, objects);
        }

        Object result = null;
        try {
            transactionManager.beginTransaction();
            result = method.invoke(proxied, objects);
            transactionManager.commit();
        } catch (Exception e) {
            transactionManager.rollback();
            throw e;
        }
        return result;
    }
}
